package main

import (
	"fmt"
	"net"
	"strings"
)

func HandleConnect(conn net.Conn) {
	defer conn.Close()
	//获取连接客户端addr
	addr := conn.RemoteAddr()
	fmt.Println(addr, "客户端连接成功")
	buf := make([]byte, 4096)
	for {
		n, err := conn.Read(buf)
		if "exit\r\n" == string(buf[:n]) || "exit\n" == string(buf[:n]) {
			fmt.Println("接收到客户端退出请求，服务器关闭")
			return
		}
		if n == 0 {
			fmt.Println("检测到客户端断开连接")
			return
		}
		if err != nil {
			fmt.Println("conn.read error")
			return
		}
		fmt.Println("读取到客户端的数据为", buf[:n])
		//小写转大写会发数据
		strings.ToUpper(string(buf[:n]))
		_, _ = conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
	}
}
func main() {
	listener, err := net.Listen("tcp", "192.168.1.121:8001")
	if err != nil {
		fmt.Println("net.listen error")
		return
	}
	fmt.Println("等待连接客户端")
	defer listener.Close()
	//监听客户端连接请求
	for {
		conn, err2 := listener.Accept()
		if err2 != nil {
			fmt.Println("listener accept error")
			return
		}
		//具体完成客户端和服务端数据通信
		go HandleConnect(conn)
	}

}
